package com.example.app01.model

class CardMatchingGame(private val count: Int) {
    var score = 0
        private set

    private val cards: MutableList<Card>
    private var firstSelectedIndex: Int = -1
    private var secondSelectedIndex: Int = -1
    private var isWaitingForFlipBack = false

    companion object {
        const val MISMATCH_PENALTY = 2
        const val MATCH_BONUS = 4
        const val COST_TO_CHOOSE = 1
    }

    init {
        // 创建匹配对（8对卡片）
        cards = createCardPairs()
    }

    private fun createCardPairs(): MutableList<Card> {
        val deck = Deck()
        val tempCards = mutableListOf<Card>()

        // 创建8对相同的卡片
        for (i in 0 until 8) {
            val card = deck.drawRandomCard()
            if (card != null) {
                // 添加两张相同的牌
                tempCards.add(card)
                tempCards.add(Card(card.suit, card.rank)) // 创建相同的副本
            }
        }

        // 洗牌后返回
        return tempCards.shuffled().toMutableList()
    }

    fun cardAtIndex(index: Int): Card {
        return cards[index]
    }

    fun chooseCardAtIndex(index: Int): Pair<Boolean, Int> {
        val card = cardAtIndex(index)

        // 如果卡片已经匹配或正在等待翻转，忽略点击
        if (card.isMatched || isWaitingForFlipBack || card.isChosen) {
            return Pair(false, 0)
        }

        // 扣翻牌成本
        score -= COST_TO_CHOOSE

        // 翻转卡片
        card.isChosen = true

        // 处理第一张卡片选择
        if (firstSelectedIndex == -1) {
            firstSelectedIndex = index
            return Pair(false, 0) // 还需要选择第二张
        }

        // 处理第二张卡片选择
        secondSelectedIndex = index
        val firstCard = cardAtIndex(firstSelectedIndex)

        // 检查是否匹配
        val matchScore = firstCard.match(arrayOf(card))

        if (matchScore > 0) {
            // 匹配成功
            score += matchScore * MATCH_BONUS
            firstCard.isMatched = true
            card.isMatched = true
            resetSelection()
            return Pair(true, matchScore * MATCH_BONUS) // 匹配成功，不需要翻转
        } else {
            // 不匹配
            score -= MISMATCH_PENALTY
            isWaitingForFlipBack = true
            return Pair(false, -MISMATCH_PENALTY) // 需要翻转回去
        }
    }

    fun flipBackUnmatchedCards() {
        if (firstSelectedIndex != -1 && secondSelectedIndex != -1) {
            val firstCard = cardAtIndex(firstSelectedIndex)
            val secondCard = cardAtIndex(secondSelectedIndex)

            if (!firstCard.isMatched && !secondCard.isMatched) {
                firstCard.isChosen = false
                secondCard.isChosen = false
            }
        }
        resetSelection()
        isWaitingForFlipBack = false
    }

    private fun resetSelection() {
        firstSelectedIndex = -1
        secondSelectedIndex = -1
    }

    fun resetGame() {
        score = 0
        resetSelection()
        isWaitingForFlipBack = false
        cards.clear()
        cards.addAll(createCardPairs())
    }

    val isGameFinished: Boolean
        get() = cards.all { it.isMatched }

    val isWaitingForFlip: Boolean
        get() = isWaitingForFlipBack

    val selectedCardIndices: Pair<Int, Int>
        get() = Pair(firstSelectedIndex, secondSelectedIndex)
}